<template>
  <el-breadcrumb separator="/" class="app-breadcrumb">
    <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
      <span v-if="index === levelList.length - 1 || item.redirect === 'noRedirect'" >
        {{ item.meta.title }}
      </span>
      <a v-else @click="handleLink(item)"> {{ item.meta.title }}</a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup name="Breadcrumb">
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const levelList = ref([])

function getBreadcrumb() {
  let matched = route.matched.filter(
    item => item.meta && item.meta.title
  )
  const first = matched[0]
  if (!isDashboard(first)) {
    matched = [{ path: '/index', meta: { title: '首页' } }].concat(matched)
  }
  levelList.value = matched
}

function handleLink(item) {
  const { path } = item
  router.push(path)
}

function isDashboard(route) {
  const name = route && route.name
  if (!name) {
    return false
  }
  return name.trim().toLowerCase() === 'index'
}

watch(
  () => route.fullPath,
  () => {
    getBreadcrumb()
  },
  {
    immediate: true
  }
)
onMounted(() => {
  getBreadcrumb()
})
</script>

<style scoped lang="scss">
.el-breadcrumb__inner {
  color: rgba(255, 255, 255, 0.65);
}

.el-breadcrumb__inner a {
  color: rgba(255, 255, 255, 0.65) !important;
}

.el-breadcrumb__inner a:hover {
  color: rgb(255, 255, 255) !important;
}

:deep(.el-breadcrumb__separator) {
  color: #FFFFFFA6 !important;
}

.el-breadcrumb__inner > span:last-child {
  color: rgba(255, 255, 255, 0.95) !important;
}

.app-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
